/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.domain.KwPublicExam;
import me.zhengjie.kwService.PublicExamService;
import me.zhengjie.service.KwPublicExamService;
import me.zhengjie.service.dto.KwPublicExamQueryCriteria;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.UploadUtils;
import me.zhengjie.util.ruoyiexcel.RuoYiConfig;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @date 2021-06-28
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "考试公开信息表前端控制器管理")
@RequestMapping("/api/kwPublicExam")
public class KwPublicExamController {

    private final KwPublicExamService kwPublicExamService;
    private final PublicExamService publicExamService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('kwPublicExam:list')")
    public void download(HttpServletResponse response, KwPublicExamQueryCriteria criteria) throws IOException {
        kwPublicExamService.download(kwPublicExamService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询考试公开信息表前端控制器")
    @ApiOperation("查询考试公开信息表前端控制器")
    @PreAuthorize("@el.check('kwPublicExam:list')")
    public ResponseEntity<Object> query(KwPublicExamQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(kwPublicExamService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增考试公开信息表前端控制器")
    @ApiOperation("新增考试公开信息表前端控制器")
    @PreAuthorize("@el.check('kwPublicExam:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody KwPublicExam resources) {
        return new ResponseEntity<>(kwPublicExamService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改考试公开信息表前端控制器")
    @ApiOperation("修改考试公开信息表前端控制器")
    @PreAuthorize("@el.check('kwPublicExam:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody KwPublicExam resources) {
        kwPublicExamService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除考试公开信息表前端控制器")
    @ApiOperation("删除考试公开信息表前端控制器")
    @PreAuthorize("@el.check('kwPublicExam:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        kwPublicExamService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    /*----------------------------------------------------------------------------------------*/
    @PostMapping("/upload")
    @ApiOperation(value = "图片上传")
    public BaseResponse upload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return BaseResponse.failed("请选择文件");
        }
        String filename = file.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!"jpg".equals(prefix) && !"jpeg".equals(prefix) && !"png".equals(prefix) && !"gif".equals(prefix)) {
            return BaseResponse.failed("请上传jpg、jpeg、png、gif格式的图片");
        }
        filename = UUID.randomUUID().toString().replace("-", "") + "." + prefix;

        // 存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile();
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        String url = fileDir.getAbsolutePath();
        try {
            // 构建真实的文件路径
            File newFile = new File(url + File.separator + filename);
            System.err.println(newFile.getAbsolutePath());
            // 上传图片到 -》 “绝对路径”
            file.transferTo(newFile);
            String imgUrl = "8000/" + RuoYiConfig.getImgPath().replace("F:/", "") + filename;
            return BaseResponse.ok("上传成功", "static/" + filename);
        } catch (IOException e) {
            e.printStackTrace();
            return BaseResponse.failed("上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/deleteFile")
    @ApiOperation("删除图片")
    public BaseResponse deleteFile(@RequestBody List<String> paths) {
        if (paths.size() > 0 && paths != null) {
            for (String path : paths) {
                int lastIndexOf = path.lastIndexOf("/");
                String imgPath = path.substring(lastIndexOf + 1, path.length());
                imgPath = RuoYiConfig.getImgPath() + "/" + imgPath;
                File file = new File(imgPath);
                if (file.exists()) {
                    file.delete();
                }
            }
            return BaseResponse.ok("删除成功");
        }
        return BaseResponse.failed("没有图片可删除");
    }
}